package com.yuguoxy.mytomcat;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.File;
public class UploadFileServlet extends YGHttpServlet {
    @Override
    public void doGet(YGHttpRequest request, YGHttpResponse response) {

    }

    @Override
    public void doPost(YGHttpRequest request, YGHttpResponse response) {
        String tempFile = "D:\\myupload\\tempfile";
        String path = "D:\\myupload\\images";
        //读取临时文件内容保存到指定文件
        try {
            saveFile(tempFile,path);

            response.write("上传文件成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void saveFile(String tempath,String path) throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile(tempath,"r");
        randomAccessFile.readLine(); // 边界
        String fileMessage = randomAccessFile.readLine();
        String fileName = getFileName(fileMessage);
        String contentType = randomAccessFile.readLine().split(":")[1]; //content-type
        randomAccessFile.readLine(); //回车换行

        long startPoint = randomAccessFile.getFilePointer();
        randomAccessFile.seek(randomAccessFile.length());
        long endPoint = randomAccessFile.getFilePointer();
        int j = 1; // \n
        while (endPoint >=0 && j <=2){
            endPoint--;
            randomAccessFile.seek(endPoint);
            if(randomAccessFile.readByte() == '\n'){
                j++;
            }
        }
        endPoint = endPoint-1;
        File saveFile = new File(path,fileName);
        RandomAccessFile randomFile = new RandomAccessFile(saveFile,"rw");
        randomAccessFile.seek(startPoint);
        while (startPoint < endPoint){
            randomFile.write(randomAccessFile.readByte());
            startPoint = randomAccessFile.getFilePointer();
        }
        randomAccessFile.close();
        randomFile.close();
        new File(tempath).delete(); //删除临时文件
    }
    public String getFileName(String fileMessage){
        String line = fileMessage.split(";")[2];
        String tempFileName = line.split("=")[1]; // "qq.jpg"
        return tempFileName.substring(1,tempFileName.length()-1);
    }
}
